package com.haiheng.voiceandbook.commo

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Process
import android.text.TextUtils
import android.util.Log
import android.view.*
import android.widget.Toast
import com.haiheng.voiceandbook.BuildConfig
import com.haiheng.voiceandbook.Constants
import com.haiheng.voiceandbook.Constants.Companion.SP_APPID
import com.haiheng.voiceandbook.Constants.Companion.SP_LIBRARY_CODE
import com.haiheng.voiceandbook.MyApplication
import com.haiheng.voiceandbook.R
import com.haiheng.voiceandbook.databinding.DialogSettingBinding
import com.haiheng.voiceandbook.utils.AppUtils
import com.haiheng.voiceandbook.utils.DisplayUtil
import com.haiheng.voiceandbook.utils.SpUtil
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import android.content.Context.ACTIVITY_SERVICE

import android.app.ActivityManager
import android.content.Intent
import android.os.Environment
import com.haiheng.voiceandbook.Constants.Companion.SP_MAON_ORDER_CONFIG
import com.haiheng.voiceandbook.Constants.Companion.SP_SCREEN_SAVER_PIC_TIME
import com.haiheng.voiceandbook.Constants.Companion.SP_SCREEN_SAVER_TIME
import com.haiheng.voiceandbook.Constants.Companion.SP_TAIZHOU_H5_URL
import org.geometerplus.android.util.OrientationUtil.startActivity
import java.io.File


/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2021/11/22 0022
 * @Version: 1.0
 */
class SettingDialog : Dialog {
    var mContext : Activity
    var binding : DialogSettingBinding? = null
    constructor(context: Activity) : super(context, R.style.my_dialog_style){
        this.mContext = context
        init();
    }

    public fun init() {
        binding = DialogSettingBinding.inflate(LayoutInflater.from(mContext),null,false)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(binding!!.root)
        setCancelable(true)
        setCanceledOnTouchOutside(false)
        val win: Window? = getWindow()
        if (win != null) {
            win.decorView.setPadding(0, 0, 0, 0)
            val lp = win.attributes
            lp.width = DisplayUtil.getScreenWidth(mContext)-DisplayUtil.dip2px(mContext,30f)
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT
            win.attributes = lp
            win.setGravity(Gravity.CENTER)
        }
        if (Constants.isOpenYouShengXin()){
            binding!!.llH5Url.visibility = View.VISIBLE
        }else{
            binding!!.llH5Url.visibility = View.GONE
        }
        binding!!.etAppid.setText(SpUtil.getString(mContext,SP_APPID,Constants.getAppId()))
        binding!!.etLibraryCode.setText(SpUtil.getString(mContext, SP_LIBRARY_CODE,Constants.getLibraryCode()))
        binding!!.etMainOrderConfig.setText(SpUtil.getString(mContext, SP_MAON_ORDER_CONFIG,Constants.getMainOrderConfig()))
        binding!!.etH5Url.setText(SpUtil.getString(mContext, SP_TAIZHOU_H5_URL,Constants.getTaiZhouH5Url()))
        binding!!.etSreenSaverTime.setText(Constants.getSreenSaverTime().toString())
        binding!!.etSreenSaverPicTime.setText(Constants.getSreenSaverPicTime().toString())
        binding!!.switchExitPushApp.isChecked = Constants.isExitOpenApp()
        binding!!.switchOpenUrl.isChecked = Constants.isOpenYouShengXin()
        binding!!.switchOpenUrl.setOnClickListener {
            binding!!.switchOpenUrl.isChecked = !Constants.isOpenYouShengXin()
            SpUtil.putBoolean(mContext,Constants.SP_IS_OPEN_YOU_SHENG_XIN,binding!!.switchOpenUrl.isChecked)
        }
        binding?.switchSreenSaver?.isChecked = Constants.isOpenSreenSaver()
        binding!!.switchSreenSaver.setOnClickListener {
            if (binding!!.switchSreenSaver.isChecked && Constants.isPicFileExists()){
                binding!!.switchSreenSaver.isChecked = !Constants.isOpenSreenSaver()
            }else{
                binding!!.switchSreenSaver.isChecked = false
                Toast.makeText(mContext, "请将屏保图片拷贝到${Constants.SCREEN_SAVER_FILE_NAME}文件夹", Toast.LENGTH_SHORT).show()
            }
            SpUtil.putBoolean(mContext,Constants.SP_IS_OPEN_SCREEN_SAVER,binding!!.switchSreenSaver.isChecked)
        }
        binding!!.switchExitPushApp.setOnClickListener {
            binding!!.switchExitPushApp.isChecked = !Constants.isExitOpenApp()
            SpUtil.putBoolean(mContext,Constants.SP_SWITCH_EXIT_OPEN_APP,binding!!.switchExitPushApp.isChecked)
        }
        binding!!.btnSave.setOnClickListener {
            if (TextUtils.isEmpty(binding!!.etAppid.text)){
               Toast.makeText(mContext,"APPID不能为空",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(binding!!.etLibraryCode.text)){
                Toast.makeText(mContext,"图书馆编号",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (!isValidConfig(binding!!.etMainOrderConfig.text.toString())){
                Toast.makeText(mContext,"格式不符，格式:1234,对应顺序热门专辑，最新专辑，最新图书，热门图书",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            SpUtil.putString(mContext,SP_LIBRARY_CODE, binding!!.etLibraryCode.text.toString().trim())
            SpUtil.putString(mContext, SP_APPID, binding!!.etAppid.text.toString().trim())
            SpUtil.putString(mContext, SP_MAON_ORDER_CONFIG, binding!!.etMainOrderConfig.text.toString().trim())
            SpUtil.putString(mContext, SP_TAIZHOU_H5_URL, binding!!.etH5Url.text.toString().trim())
            SpUtil.putInt(mContext, SP_SCREEN_SAVER_TIME, binding!!.etSreenSaverTime.text.toString().toInt())
            SpUtil.putInt(mContext, SP_SCREEN_SAVER_PIC_TIME, binding!!.etSreenSaverPicTime.text.toString().toInt())
            Toast.makeText(mContext,"保存成功",Toast.LENGTH_SHORT).show()
            MyApplication.getInstance().changeBuglyUserDate()
//            dismiss()
        }
        binding!!.ivClose.setOnClickListener { dismiss() }
        binding!!.tvVersion.setText(BuildConfig.VERSION_NAME)
        binding!!.tvCheckUpdata.setOnClickListener {
            //检查更新
            if (AppUtils.isNotConnected(MyApplication.getInstance().applicationContext)){
                Toast.makeText(mContext,"网络异常",Toast.LENGTH_SHORT).show()
            }else{
                VersionManager.getVersionInfo(mContext,true)
            }

        }
        binding!!.btnExt.setOnClickListener {
            val intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_HOME)
            mContext.startActivity(intent)
            stopAppByKill(mContext,"com.steven.download")
            Process.killProcess(Process.myPid())
            System.exit(0)
        }
        binding!!.tvDeviceId.setText(Constants.getDevicesId())
    }


    //验证首页配置是否正确
    fun isValidConfig(config: String): Boolean {
        if (config.isEmpty()) return false
        if (config.length != 4) return false
        Log.e("dddd hwz","config:${config} result:${config.contains("1") && config.contains("2") && config.contains("3") && config.contains("4")}")
        return config.contains("1") && config.contains("2") && config.contains("3") && config.contains("4")
    }

    fun stopAppByKill(context:Context , packageName:String) {
        val activityMgr = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        activityMgr.killBackgroundProcesses(packageName)
    }
}